<template>
    <div class="wrap">
        <div id="container">
            <!-- 定义一个表格元素 -->
            <section class="detail-header">
                <div class="col-sm-12 console-title">
                    <h5 class="">实例监控</h5>
                    <div class="stayRight ">
                        <el-button @click="refreshData()">刷新</el-button>
                    </div>
                    <div class="stayRight ">
                      <el-button @click="setConfig()">默认告警设置</el-button>
                    </div>
                </div>
            </section>
            <section class="tableMain">
                <el-table :data="domains.dataArr" style="width: 100%" 
                :row-class-name="domainRowClassName"
                :default-expand-all="true" >
                    <el-table-column type="expand" width="40">
                      <template scope="props">
                        <el-table :data="props.row.instances" style="width: 100%" :show-header="false"
                        :row-class-name="insRowClassName">
                          <el-table-column width="60"></el-table-column>
                          <el-table-column prop="ip" width="200"></el-table-column>
                          <el-table-column prop="balanc"></el-table-column>
                          <el-table-column prop="maculaDSActive"></el-table-column>
                          <el-table-column prop="cbsDSActive"></el-table-column>
                          <el-table-column prop="errorCnt"> </el-table-column>
                          <el-table-column prop="avgTime" :formatter="toFixed"> </el-table-column>
                          <el-table-column prop="traffic"> </el-table-column>
                          <el-table-column prop="qps" :formatter="toFixed"> </el-table-column>
                          <el-table-column prop="cpu" :formatter="toFixed"> </el-table-column>
                          <el-table-column prop="memoryUsage" :formatter="toFixed"> </el-table-column>

                          <el-table-column width="70" align="left">
                            <template scope="scope">
                              <el-popover v-if="scope.row.warningCode && scope.row.warningCode!=='normal'" trigger="hover" placement="left">
                                <p>{{scope.row.warningTypes}}</p>
                                <div slot="reference" class="name-wrapper">
                                  <el-button type="danger" icon="warning" size="mini"></el-button>
                                </div>
                              </el-popover>
                            </template>
                          </el-table-column>

                        </el-table>
                      </template>
                    </el-table-column>
                    <el-table-column prop="name" label="模块/ip" width="220"> </el-table-column>
                    <el-table-column prop="balanc" label="负载" :formatter="formatBalanc"> </el-table-column>
                    <el-table-column prop="maculaDSActive" label="macula连接池"> </el-table-column>
                    <el-table-column prop="cbsDSActive" label="core连接池"> </el-table-column>
                    <el-table-column prop="errCnt" label="异常数" > </el-table-column>
                    <el-table-column prop="avg" label="响应时间(ms)" :formatter="toFixed"> </el-table-column>
                    <el-table-column prop="reqCnt" label="访问数"> </el-table-column>
                    <el-table-column prop="qps" label="QPS" :formatter="formatDoCol"> </el-table-column>
                    <el-table-column prop="cpuUsage" label="cpu使用数(%)" :formatter="toFixed"> </el-table-column>
                    <el-table-column prop="memUsage" label="内存使用率(%)" :formatter="toFixed"> </el-table-column>

                    <el-table-column width="70" align="left">
                      <template scope="scope">
                        <el-popover v-if="scope.row.warningCode && scope.row.warningCode!=='normal'" trigger="hover" placement="left">
                          <p>{{scope.row.warningTypes}}</p>
                          <div slot="reference" class="name-wrapper">
                            <el-button type="danger" icon="warning" size="mini"></el-button>
                          </div>
                        </el-popover>
                      </template>
                    </el-table-column>

                </el-table>
                <!-- <div class="pageSIzeblock">
                    <div class="pullright">
                        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="domains.currPage" :page-sizes="[10, 20, 50, 100]" :page-size="domains.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="domains.totalCount">
                        </el-pagination>
                    </div>
                </div> -->
            </section>

            <el-dialog title="默认预警设置" :visible.sync="defaultUpdateDialogVislble" class="customDialog team" :lock-scroll="false" size="small">
                <div class="scoreContainer tagCategory">
                    <el-form :model="defaultUpdateForm" :rules="defaultUpdateRules" ref="defaultUpdateForm" label-width="120px" class="demo-updateForm">
                        <el-form-item label="选择模块" prop="domainType" required>
                          <el-cascader
                            expand-trigger="hover"
                            :options="configTypes"
                            v-model="alarmConfigs.longId"
                            @change="setConfig">
                          </el-cascader>
                        </el-form-item>

                      <template v-if="defaultUpdateForm.id">
                        <el-form-item label="短信与邮件告警" prop="status">
                          <el-switch
                            v-model="defaultUpdateForm.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949">
                          </el-switch>
                        </el-form-item>
                        
                        <el-form-item label="沉默时间(分钟)" prop="freq">
                          <el-input placeholder="短信与邮件沉默时间" v-model="defaultUpdateForm.freq" type="number" min="1" max="2000" :maxlength="4" class="warning-setting"></el-input>
                        </el-form-item>


                        <el-form-item label="QPS" prop="qps">
                          <el-col :span="11">
                            <el-form-item prop="qps">
                              <el-input placeholder="Warning值" v-model="defaultUpdateForm.qps" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="11">
                            <el-form-item prop="qpsErr">
                              <el-input placeholder="Error值" v-model="defaultUpdateForm.qpsErr" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-form-item>


                        <el-form-item label="响应时间(ms)">
                          <el-col :span="11">
                            <el-form-item prop="avgTime">
                              <el-input placeholder="Warning值" v-model="defaultUpdateForm.avgTime" type="number" min="1" max="20000" :maxlength="5"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="11">
                            <el-form-item prop="avgTimeErr">
                              <el-input placeholder="Error值" v-model="defaultUpdateForm.avgTimeErr" type="number" min="1" max="20000" :maxlength="5"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-form-item>

                        <el-form-item label="异常数(个)">
                          <el-col :span="11">
                            <el-form-item prop="errorCnt">
                              <el-input placeholder="Warning值" v-model="defaultUpdateForm.errorCnt" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="11">
                            <el-form-item prop="errorCntErr">
                              <el-input placeholder="Error值" v-model="defaultUpdateForm.errorCntErr" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-form-item>

                        <el-form-item label="内存使用率(%)">
                          <el-col :span="11">
                            <el-form-item prop="memUsage">
                              <el-input placeholder="Warning值" v-model="defaultUpdateForm.memUsage" type="number" min="1" max="99" :maxlength="2"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="11">
                            <el-form-item prop="memUsageErr">
                              <el-input placeholder="Error值" v-model="defaultUpdateForm.memUsageErr" type="number" min="1" max="99" :maxlength="2"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-form-item>

                        <el-form-item label="CPU使用率(%)">
                          <el-col :span="11">
                            <el-form-item prop="cpuUsage">
                              <el-input placeholder="Warning值" v-model="defaultUpdateForm.cpuUsage" type="number" min="1" max="99" :maxlength="2"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="11">
                            <el-form-item prop="cpuUsageErr">
                              <el-input placeholder="Error值" v-model="defaultUpdateForm.cpuUsageErr" type="number" min="1" max="99" :maxlength="2"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-form-item>

                        <el-form-item label="Macula连接数(个)">
                          <el-col :span="11">
                            <el-form-item prop="dbMacula">
                              <el-input placeholder="Warning值" v-model="defaultUpdateForm.dbMacula" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="11">
                            <el-form-item prop="dbMaculaErr">
                              <el-input placeholder="Error值" v-model="defaultUpdateForm.dbMaculaErr" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-form-item>
                        
                        <el-form-item label="Core连接数(个)">
                          <el-col :span="11">
                            <el-form-item prop="dbCore">
                              <el-input placeholder="Warning值" v-model="defaultUpdateForm.dbCore" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                          <el-col :span="11">
                            <el-form-item prop="dbCoreErr">
                              <el-input placeholder="Error值" v-model="defaultUpdateForm.dbCoreErr" type="number" min="1" max="2000" :maxlength="4"></el-input>
                            </el-form-item>
                          </el-col>
                        </el-form-item>

                        <el-form-item label="通知对象">
                            <el-transfer 
                              filterable
                             :footer-format="{
                                noChecked: '共${total}项',
                                hasChecked: '已选${checked}/${total} 项'
                              }"
                             :titles="['未选联系人组', '已选联系人组']"  
                             v-model="defaultUpdateForm.contactIds" 
                             :data="contacts.dataArr"> 
                            </el-transfer>
                        </el-form-item>
                      </template>
                    </el-form>
                </div>

                <span slot="footer" class="dialog-footer">
                    <div class="aar-gap">
                        <div class="aar-gap-line-b">
                            <div class="aar-gap-line"></div>
                        </div>
                    </div>
                  <el-button type="primary" @click="creatDefaultSubmit('defaultUpdateForm')">确 定</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import { queryAllDomains, queryConfigTypes, queryAlarmConfigs, setAlarmConfig } from '@/api/instanceData'
import { getAlarmContactsGroupList } from '@/api/alarmRulesData'
import { Loading } from 'element-ui'
export default {
  data() {
    return {
      domains: {
        dataArr: [],
        currPage: 1,
        pageSize: 10,
        totalCount: 0,
        type: '',
        searchName: '',
        selection: [],
        types: []
      },
      contacts: {
        dataArr: []
      },
      configTypes: {

      },
      alarmConfigs: {
        dataArr: [],
        longId: []
      },
      defaultUpdateDialogVislble: false,
      defaultUpdateForm: {
        id: '',
        freq: '',
        qps: '',
        qpsErr: '',
        avgTime: '',
        avgTimeErr: '',
        errorCnt: '',
        errorCntErr: '',
        memUsage: '',
        memUsageErr: '',
        cpuUsage: '',
        cpuUsageErr: '',
        dbMacula: '',
        dbMaculaErr: '',
        dbCore: '',
        dbCoreErr: '',
        contactIds: []
      },
      defaultUpdateRules: {
        freq: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        qps: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        qpsErr: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        errorCnt: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        errorCntErr: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        dbMacula: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        dbMaculaErr: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        dbCore: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        dbCoreErr: [
          { validator: this.checkCnt, trigger: 'blur' }
        ],
        avgTime: [
          { validator: this.checkSpeed, trigger: 'blur' }
        ],
        avgTimeErr: [
          { validator: this.checkSpeed, trigger: 'blur' }
        ],
        memUsage: [
          { validator: this.checkRate, trigger: 'blur' }
        ],
        memUsageErr: [
          { validator: this.checkRate, trigger: 'blur' }
        ],
        cpuUsage: [
          { validator: this.checkRate, trigger: 'blur' }
        ],
        cpuUsageErr: [
          { validator: this.checkRate, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getAllDomains(1)
    this.getContacts()
    this.getConfigTypes()
    this.getAlarmConfigs()
  },
  methods: {
    refreshData() {
      this.domains.type = ''
      this.getAllDomains(1)
      this.getContacts()
      this.getConfigTypes()
      this.getAlarmConfigs()
    },
    getAllDomains(currPage) {
      this.domains.currPage = currPage
      var loadId = Loading.service({ text: '加载中，请稍等' })
      var listQuery = { type: this.domains.type, keyword: this.domains.searchName, important: 1 }
      queryAllDomains(listQuery).then(response => {
        console.log(response.data.data.domains)
        this.domains.dataArr = response.data.data.domains
        loadId.close()
      }).catch(_ => {
        loadId.close()
      })
    },
    getContacts() {
      this.contacts.dataArr = []
      getAlarmContactsGroupList().then(response => {
        response.data.data.forEach(function(element) {
          this.contacts.dataArr.push({
            key: element.id,
            label: element.name
          })
        }, this)
      }).catch(_ => {
      })
    },
    getConfigTypes() {
      queryConfigTypes().then(response => {
        this.configTypes = response.data.rows
      }).catch(_ => {
      })
    },
    getAlarmConfigs() {
      queryAlarmConfigs().then(response => {
        this.alarmConfigs = response.data.rows
      }).catch(_ => {
      })
    },
    setConfig() {
      var longId = alarmConfigs.longId
      if(!longId.length) {
        return
      }
      let id = longId[longId.length - 1]
      if(id) {
        return
      }
      for(var i in this.alarmConfigs) {
        if(this.alarmConfigs[i].id == id) {
          this.defaultUpdateForm = JSON.parse(JSON.stringify(this.alarmConfigs[i]))
          this.defaultUpdateForm.id = id
          break;
        }
      }
      this.defaultUpdateDialogVislble = true
    },
    // 负载，连接池，线程数，cpu，内存，内存使用率
    formatBalanc(row, column) {
      var bs = 0
      row.instances.forEach(function(item) {
        if (item.balanc) {
          bs += item.balanc
        }
      })
      return Number(bs / row.instances.length).toFixed(2)
    },
    toFixed(row, column) {
      return Number(row[column.property]).toFixed(2)
    },
    formatDoCol(row, column) {
      var val = 0
      row.instances.forEach(function(item) {
        if (item[column.property]) {
          val += item[column.property]
        }
      })
      return Number(val).toFixed(2)
    },
    domainRowClassName(row) {
      return row.warningCode
    },
    insRowClassName(item) {
      return item.warningCode
    },
    checkCnt(rule, value, callback) {
      if (!value || value < 1 || value > 2000) {
        callback(new Error('阈值区间为1-2000'))
      } else {
        callback()
      }
    },
    checkSpeed(rule, value, callback) {
      if (!value || value < 1 || value > 20000) {
        callback(new Error('阈值区间为1-20000'))
      } else {
        callback()
      }
    },
    checkRate(rule, value, callback) {
      if (!value || value < 1 || value > 99) {
        callback(new Error('阈值区间为1-99'))
      } else {
        callback()
      }
    },
    handleCurrentChange(currPage) {
      this.domains.currPage = currPage
      this.getDomains(currPage)
    },
    handleSizeChange(pageSize) {
      this.domains.pageSize = pageSize
      this.getDomains(1)
    },
    creatDefaultSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var loadId = Loading.service({ text: '正在保存' })
          var jsonData = {}
          jsonData = JSON.parse(JSON.stringify(this.defaultUpdateForm))
          jsonData.contactId = this.defaultUpdateForm.contactIds.join(',')
          var _this = this
          const resetTable = function() {
            _this.defaultUpdateDialogVislble = false
            _this.getAlarmConfigs()
          }
          setAlarmConfig(jsonData).then(response => {
            loadId.close()
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success'
            })
            resetTable()
          }).catch(_ => {
            loadId.close()
          })
        }
      })
    }
  }
}
</script>


<style lang="scss">
.warning-setting{
  width:45%;
}
.error-setting{
  width:45%;
}
.el-table .warning {
    background: #dddd99;
}
.el-table .error {
    background: #dd9999;
}
.detail-header{
    padding: 0 15px;
    margin-bottom: 10px;
    overflow: hidden;
    .console-title{
        padding: 16px 0px;
        min-height: 70px;
        border-bottom: 1px solid #eee;
        position: relative;
        h5{
            display: inline-block;
            text-indent: 8px;
            border-left: 2px solid #88B7E0;
            margin: 8px 0;
            margin-right: 8px;
            vertical-align: top;
        }
        .stayRight{
            position: absolute;
            top: 15px;
            right: 0;
            overflow: hidden;
            .refresh{
                float: left;
                margin-right: 10px;
                color: #333;
                border: 1px solid #ddd;
                background-color: #F7F7F7;
            }
            .creatSite{
                float: left;
            }
        }
    }
}
.searchSel{
    width: 150px;
    display: inline-block;
}
.searchIpt{
    width: 100%;
    display: inline-block;
}
.searchbtn{
    width: 100px;
    display: inline-block;
}
.searchBar{
    padding: 0 10px;
}
.tableMain{
    padding: 10px;
}
.typeform{
    display: inline;
    .form-control{
        border: none;
        padding: 0;
        box-shadow:none;
        display: inline;
        height:30px;
        width:60%;
    }
}
.spantype{
    display: inline;
}
.pageSIzeblock{
    overflow: hidden;
    padding: 10px 0;
    .pullright{
        float: right;
    }
}

.el-table__expanded-cell{padding: 0px 0px;}
.instanceTypeClass .el-select{width:800px;}
.delBtn{font-weight:bold;font-size:13px;position:absolute;right:0px;top:8px;background:#fff;}
</style>


